package com.lm.lua.config;

import org.luaj.vm2.Globals;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.jse.JsePlatform;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class LuaScriptManager {

    private final Globals globals;

    public LuaScriptManager() {
        // 初始化 Lua 环境
        this.globals = JsePlatform.standardGlobals();
    }

    public LuaValue loadScript(String scriptPath) {
        try (Reader reader = new FileReader(new File(scriptPath))) {
            return globals.load(reader, scriptPath);
        } catch (Exception e) {
            throw new RuntimeException("Failed to load Lua script: " + scriptPath, e);
        }
    }

    public LuaValue executeFunction(LuaValue script, String functionName, LuaValue... args) {
        LuaValue function = script.get(functionName);
        if (!function.isfunction()) {
            throw new RuntimeException("Function " + functionName + " not found in script");
        }

        return function.invoke(args).arg(0);
    }
}